﻿using System;
using System.Linq;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Notes.Model;
using System.Windows;
using System.IO.IsolatedStorage;
using Microsoft.Live;
using Microsoft.Live.Controls;

namespace Notes
{
    public partial class DetailsPage : PhoneApplicationPage
    {
        private Note _Note;
        // Constructor
        public DetailsPage()
        {
            InitializeComponent();
        }

        // When page is navigated to set data context to selected item in list
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            string selectedIndex = "";
            if (NavigationContext.QueryString.TryGetValue("selectedItem", out selectedIndex))
            {
                int index = int.Parse(selectedIndex);
                DataContext = App.ViewModel.Notes[index];
                _Note = App.ViewModel.Notes[index];
            }
        }

        private void ApplicationBarSave_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(ContentTitle.Text) && !String.IsNullOrWhiteSpace(ContentTitle.Text))
            {
                Note n = new Note();
                
				if (_Note != null)
                {
                    var NoteInDB = from Note note in App.db.Notes where note.Id == _Note.Id select note;
                    n = NoteInDB.First();
				}

                n.Title = ContentTitle.Text;
                n.Text = ContentText.Text;
				n.Edited = DateTime.Now;
				
				if (_Note == null)
				{
                    App.db.Notes.InsertOnSubmit(n);
                }

                App.db.SubmitChanges();

				NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
				NavigationService.RemoveBackEntry();
            }
        }

        private void ApplicationBarDel_Click(object sender, EventArgs e)
        {
            if (_Note != null)
            {
                var NoteInDB = from Note note in App.db.Notes where note.Id == _Note.Id select note;
                Note nn = NoteInDB.First();
                if (MessageBox.Show("Please, confirm note deletion.", "Warning", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    App.db.Notes.DeleteOnSubmit(nn);
                    App.db.SubmitChanges();
                    NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
					NavigationService.RemoveBackEntry();
                }
            }
            else { return; }
        }
    }
}